<?php
/**
 * 尚善福· 购物车的逻辑处理
 * ============================================================================
 * 版权所有 2017-2022 北京优特世纪科技有限公司，并保留所有权利。
 * 网站地址: http://www.unitewww.com；
 * ============================================================================
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * @since: 1.0
 * @version: 1.0
 **/
namespace Home\Controller;
use Think\Controller;
use Home\Model\CartModel;
class CartController extends BaseController {
    //初始化程序
    public function _initialize(){
        parent::_initialize();
        //实例化相关表
        $usident = M("user");
        //获取数据
        $uid = session('user_auth.usid');
        $user = $usident->where("`us_uid`='".$uid ."'")->find();
        $this->assign('user',$user);
        $conf = tpCache('sIno');
        $this->assign('conf',$conf);
        $this->assign('cart','active');
    }
    /**
    +--------------------------------------------------------------------------
     * 实现获取购物车列表
     * @author:XC跃
     * @date :2018-10-18
    +--------------------------------------------------------------------------
     */
    public function cart(){
        $this->display();
    }
    //ajax 请求获取购物车列表
    public function ajaxCartList(){
        $usid = session('user_auth.usid');
        //echo $usid;die;
        //实例化相关Model
        $cidentr = new CartModel();
        //实例化相关表
        $cident = M('cart');
        $post_gnums = I("post.goods_num"); // goods_num 购物车商品数量
        $post_check = I("post.cart_select"); // 购物车选中状态
        //dump($post_gnums);
        $cartList = $cident->where("`ca_uid`='".$usid."'")->select();
//        dump($cartList);
        // 修改购物车数量 和勾选状态
        if($post_gnums){
            //echo $post_gnums;
            foreach($post_gnums as $key => $val){
                $data['ca_gnum']  = $val < 1 ? 1 : $val;
                $data['ca_check'] = $post_check[$key] ? 1 : 0 ;
                if(($cartList[$key]['ca_gnum'] != $data['ca_gnum']) || ($cartList[$key]['ca_check'] != $data['ca_check'])){
                    $cident->where("`ca_id`=$key")->save($data);
                }
            }
            $this->assign('select_all', $_POST['allSelect']);   //全选框
        }
        $res = $cidentr->cartList($usid,'','0','1'); // 选中的商品
        //dump($res);
        if(empty($res['total_price'])){
            $res['total_price'] = Array('fen_fee'=>0,'sum_fee'=>0,'yun_fee'=>0);
        }
//        dump( $res['total_price']);
        $this->assign('cartList',$res['cartList']); // 购物车的商品
        $this->assign('total_price', $res['total_price']); // 总计
        $this->assign('shop',array('name'=>tpCache('sBas.shopname'),'phone'=>tpCache('sBas.shoptel')));
        $this->display();
    }
    /**
    +--------------------------------------------------------------------------
     * 实现ajax将商品加入购物车
     * @author:XC跃
     * @date :2018-10-19
    +--------------------------------------------------------------------------
     */
    function addCart(){
        //接收传值
        $usid = session('user_auth.usid');
        $goid = I("post.goid");    // 商品id
        $nums = I("post.nums",1);  // 商品数量
        $color= I("post.color");   // 商品规格:颜色
        $size = I("post.size");    // 商品规格:尺寸
        $chec = I("post.check");   // 商品默认选中
        //dump(I('post.'));die;
        //实例化相关Model
        $cidnetr = New CartModel();
        $re = $cidnetr->add_cart($usid,$goid,$nums,$color,$size,$chec);
        exit(json_encode($re));
    }
    /**
    +--------------------------------------------------------------------------
     * 实现购物车第二步去结算的功能
     * @author:XC跃
     * @date :2018-10-19
    +--------------------------------------------------------------------------
     */
    public function subOrder(){
        $uid = session('user_auth.usid');
        $gid = trim(I('get.gid/d'));
        //实例化相关表
        $uident = M('user');
        //实例化相关Model
        $cidentr = new CartModel();
        if($cidentr->cart_count($uid,1)=='0'){
            $this->error('没选中商品','/Home/Cart/cart','1','text');
        }
        //获取购物车商品
        $addre= $this->ajaxAddress($uid);  //收货地址
        $cres = $cidentr->cartList($uid,$gid,'1','1',$addre);
        $ures = $uident->where("`us_uid`='".$uid."'")->field('us_uid,us_money')->find(); //获取会员信息
        $this->assign('ures',$ures);  //会员信息
        $this->assign('ares', $addre);
        $this->assign('aid',I('get.aid',$addre['ad_id']));
        $this->assign('cartList', $cres['cartList']); // 购物车的商品
        $this->assign('total_price', $cres['total_price']); // 费用总计
        $this->display();
    }
    /**
    +--------------------------------------------------------------------------
     * 实现购物车第二步去结算的功能
     * @author:XXT
     * @date :2019-11-14
    +--------------------------------------------------------------------------
     */
    public function subOrder1(){
        $uid = session('user_auth.usid');
        $gid = trim(I('get.goid'));
        $color = I('color');
        $num = I('num');
        $size = I('size');

        //实例化相关表
        $uident = M('user');
        //收货地址
        $addre= $this->ajaxAddress($uid);
        $ures = $uident->where("`us_uid`='".$uid."'")->field('us_uid,us_money')->find(); //获取会员信息


        $cres = M('daili_goods')->where(array('dg_id'=>$gid))->select();
        $cres[0]['spec'] = $size.$color;
        $sumMoney = bcmul($cres[0]['dg_price'],$num,2);
        $this->assign('ures',$ures);  //会员信息
        $this->assign('ares', $addre);
        $this->assign('gid', $gid);

        $this->assign('aid',I('get.aid',$addre['ad_id']));
        $this->assign('cartList',$cres); // 购物车的商品
        $this->assign('total_price',$sumMoney); // 费用总计
        $this->assign('num',$num); // 费用总计
        $this->display();
    }
    /**
    +--------------------------------------------------------------------------
     * 实现购物车第三步支付订单的功能
     * @author:XC跃
     * @date :2018-10-19
    +--------------------------------------------------------------------------
     */
    public function payOrder(){
        $uid = session('user_auth.usid');
        //实例化相关表
        $usident = M('user');
        $orident = M('order');
        if(IS_POST){
            $batch= trim(I('post.batch'));
            $pays= trim(I('post.paytype'));
            $pwds = trim(I('post.pwd'));
            $orFind = $orident->where("`or_batch`='".$batch."'")->find();
            $usFind = $usident->where("`us_uid`='".$uid."'")->field('us_money,us_frozen,us_pwds')->find();
            if(count($orFind)!=0){
                //判断支 付 类 型
                if('1'==$pays){
                    $frozen = bcsub($usFind['us_frozen'],$orFind['or_jmon'],2);
                    if($frozen<0){
                        $res= array('status'=>-1,'info'=>'余额不足，更换支付方式'); // 返回结果状态
                        exit(json_encode($res));
                    }
                    //$payment = '支付宝支付';
                    $url = U('Talipay/orderPay',array('oid'=>$orFind['or_batch']));
                    $mes = array('status'=>1,'info'=>"支付宝支付正在跳转",'oid'=>$batch,'url'=>$url);
                    $this->ajaxReturn($mes);
                }elseif('2'==$pays){
//                    判断支付密码
                    if(md5($pwds) != $usFind['us_pwds']){
                        $res= array('status'=>-1,'msg'=>'支付密码错误'); // 返回结果状态
                        exit(json_encode($res));

                    }else{
                        $frozen = bcsub($usFind['us_frozen'],$orFind['or_jmon'],2);
                        $money = bcsub($usFind['us_money'],$orFind['or_xmon'],2);
                        if($money<0 || $frozen<0){
                            $res= array('status'=>-1,'info'=>'余额不足，更换支付方式'); // 返回结果状态
                            exit(json_encode($res));
                        }
                        //支付完成修改订单
                        update_pay_status($orFind['or_batch'], 2);
                        $res= array('status'=>1,'info'=>'订单支付成功','url'=>'/Home/Order/orderList'); // 返回结果状态
                        //dump($res);
                    }
                exit(json_encode($res));
                }elseif('3'==$pays){
                    $frozen = bcsub($usFind['us_frozen'],$orFind['or_jmon'],2);
                    if($frozen<0){
                        $res= array('status'=>-1,'info'=>'余额不足，更换支付方式'); // 返回结果状态
                        exit(json_encode($res));
                    }
                    //$payment = '微信支付';
                    $url = '/Home/WxPay/orderPay?oid='.$orFind['or_batch'];
                    $mes = array('status'=>1,'info'=>"微信支付正在跳转",'url'=>$url);
                    $this->ajaxReturn($mes);
                }
            }else{
                $res= array('status'=>-1,'info'=>'订单记录不存在'); // 返回结果状态
                exit(json_encode($res));
            }
        }
        else{
            $oid = trim(I('get.oid/d'));
            //$batch= trim(I('post.batch'));
            //获取相关数据
            $orFind = $orident->where("`or_id`='".$oid."' and `or_uid`='".$uid."'")->find();
            if(count($orFind)==0){
                $this->error('订单不存在','/Home/Order/orderList');
            }

            //判断订单是否支付
            if($orFind['or_pstate']=='2'){
                $this->error('此单已支付','/Home/Order/orderList');
            }
            $orFind['addre'] = addreSerialize($orFind['or_add'],'2');
            $this->assign('res',$orFind);
            $this->display();
        }
    }
    /**
    +--------------------------------------------------------------------------
     * Ajax 获取订单商品价格和提交订单
     * @author:XC跃
     * @date :2018-10-19
    +--------------------------------------------------------------------------
     */
    public function addOrder(){
        $uid = session('user_auth.usid');
        //实例化相关表
        $cident = M('cart');
        $usident = M('user');
        $conf = tpCache('sIno');
        //实例化相关Model
        $cidentr = new CartModel();
        $add_id = trim(I("post.add_id"));   // 收货地址id
        $umoney = trim(I("post.umoney",0)); // 使用余额
        $points = trim(I("post.points",0)); // 使用积分
        $umoney = $umoney ? $umoney : 0;
        $points = $points ? $points : 0;
        //判断相关信息
        if($cidentr->cart_count($uid,1)=='0'){
            exit(json_encode(array('status'=>-1,'msg'=>'你的购物车没有选中商品')));
        }if(!$add_id){
            exit(json_encode(array('status'=>-1,'msg'=>'请先填写收货人信息'))); // 返回结果状态
        }
        $addre= $this->ajaxAddress($uid);  //收货地址
        $cart_good = $cident->where("`ca_uid`='".$uid."' and `ca_check`=1")->select();
        $result = calculate_price($uid,$cart_good,$umoney='0',$addre);
//         if(!$cu_id){
//             $result = calculate_price($uid,$cart_good,$umoney,$points,'');
//         }else{
//             $coupon = $cuident->where("`cu_id`='".$cu_id."'")->field('cu_money')->find();
//             $result = calculate_price($uid,$cart_good,$umoney,$points,$coupon['cu_money']);
//         }
        $user = $usident->where("`us_uid`='".$uid ."'")->find();
        if($user['us_daili']==1){
            $car_price = array(
              'totalFee' => $result['total_amount'], // 商品总价
              'amountFee'=> $result['order_amount'], // 应付余额
              'umoney'   => $result['umoney'],       // 使用余额
              'pointsFee'=> $result['order_energy'], // 应付积分
              'shipFee'  => $result['ship_price'],   // 物流费
              'points'   => $result['energy'],       // 使用积分
            );
        }elseif($user['us_daili']==4){
            $car_price = array(
              'totalFee' => $result['total_amount'], // 商品总价
              'amountFee'=> $result['order_amount'], // 应付余额
              'umoney'   => $result['umoney'],       // 使用余额
              'pointsFee'=> $result['order_energy'], // 应付积分
              'shipFee'  => $result['ship_price'],   // 物流费
              'points'   => $result['energy'],       // 使用积分
            );
        }elseif($user['us_daili']==7){
            $car_price = array(
              'totalFee' => $result['total_amount'], // 商品总价
              'amountFee'=> $result['order_amount'], // 应付余额
              'umoney'   => $result['umoney'],       // 使用余额
              'pointsFee'=> $result['order_energy'], // 应付积分
              'shipFee'  => $result['ship_price'],   // 物流费
              'points'   => $result['energy'],       // 使用积分
            );
        }else{
            $car_price = array(
              'totalFee' => $result['total_amount'], // 商品总价
              'amountFee'=> $result['order_amount'], // 应付余额
              'umoney'   => $result['umoney'],       // 使用余额
              'pointsFee'=> $result['order_energy'], // 应付积分
              'shipFee'  => $result['ship_price'],   // 物流费
              'points'   => $result['energy'],       // 使用积分
            );
        }
        //提交订单
        if($_REQUEST['act'] == 'submit_order'){
            $res = $cidentr->addOrder($uid,$add_id,$result,'1'); // 添加订单
            //$result = array('status'=>1,'msg'=>'提交订单成功','result'=>'1'); // 返回新增的订单id
            exit(json_encode($res));
        }else{
            $return_arr = array('status'=>1,'result'=>$car_price); // 返回结果状态
            exit(json_encode($return_arr));
        }
    }
    /**
    +--------------------------------------------------------------------------
     * ajax 获取用户收货地址 用于购物车确认订单页面
     * @author:XC跃
     * @date :2018-10-19
    +--------------------------------------------------------------------------
     */
    public function ajaxAddress($uid){
        $aid = trim(I('get.aid'));
        //echo $aid;
        //实例化相关表
        $aident = M("address");
        if(empty($aid)){
            $ares = $aident->where("`ad_uid`='".$uid."'")->order("ad_default asc")->find();
        }else{
            $ares = $aident->where("`ad_uid`='".$uid."' and `ad_id`='".$aid."'")->find();
        }
        return $ares;
    }
    /**
    +--------------------------------------------------------------------------
     * 实现获取收货地址列表
     * @author:XC跃
     * @date :2018-06-05
    +--------------------------------------------------------------------------
     */
    public function addreList(){
        $uid = session('user_auth.usid');
        //实例化相关表
        $aident = M('address');
        $adList = $aident->where("`ad_uid`='".$uid."'")->order("`ad_default` asc,`ad_id` desc")->select();
        $this->assign('list',$adList);
        $this->assign('type',trim(I('get.type','')));
        $this->display();
    }
    /************************** 会员激活成功后 领取礼包的功能 ********************************/
    /**
    +--------------------------------------------------------------------------
     * 实现获取礼品商品列表
     * @author:XC跃
     * @date :2018-06-15
    +--------------------------------------------------------------------------
     */
    public function userGift(){
        //实例化相关表
        $prident = M('prop');
        //获取兑换列表
        $prList = $prident->where("`gp_sale`='1'")->order("gp_gid asc")->select();
        $this->assign('list',$prList);
        $this->display();
    }
    /**
    +--------------------------------------------------------------------------
     * 实现确认礼品商品订单信息
     * @author:XC跃
     * @date :2018-12-29
    +--------------------------------------------------------------------------
     */
    public function confirmGift(){
        cookie('goid',trim(I('get.id/d')),'3600');  //商品ID
        $goid = cookie('goid');
        $usid = session('user_auth.usid');
        //实例化相关表
        $prident = M('prop');
        //获取商品信息
        $goFind = $prident->where("`gp_id`='".$goid."' and `gp_sale`=1")->find();
        $addre= $this->ajaxAddress($usid);  //收货地址
        $this->assign('ares', $addre);
        $this->assign('aid',I('get.aid',$addre['ad_id']));
        $this->assign('gore',$goFind);
        $this->display();
    }
    /**
    +--------------------------------------------------------------------------
     * 实现提交礼品订单的功能
     * @author:XC跃
     * @date :2018-12-29
    +--------------------------------------------------------------------------
     */
    public function addGift(){
        $uid = session('user_auth.usid');
//        //实例化相关表
        $usident = M('user');
        $grident = M('grade');
        $prident = M('prop');
        $poident = M('prop_order');
        $add_id = trim(I("post.add_id"));   // 收货地址id
        $goodId = trim(I('post.gid/d'));    // 商品ID

        if(!IS_POST){
            $this->error('非法提交','/Home/Index/index');
        }
        if(!isset($uid)){
            return array('status'=>0,'url'=>U('Login/login'));
        }
        //判断相关信息
        if(!$add_id){
            exit(json_encode(array('status'=>-1,'msg'=>'请先填写收货人信息'))); // 返回结果状态
        }
        //获取会员信息
        $usFind = $usident->where("`us_uid`='".$uid."'")->field('us_uid,us_pid,us_money,us_gid')->find();
        //获取商品信息
        $prFind = $prident->where("`gp_id`='".$goodId."' and `gp_sale`=1")->find();
        if(count($prFind)=='0'){
            exit(json_encode(array('status'=>-1,'msg'=>'商品参数错误'))); // 返回结果状态
        }
        //1、执行添加订单
        $odata['or_uid']   = $uid; // 用户id
        $odata['or_batch'] = $batch = Date('YmdHis').rand(10000,99999); // 订单编号
        $odata['or_goid']   = $prFind['gp_id'];
        $odata['or_gname']   = $prFind['gp_name'];
        $odata['or_addre']   = addreSerialize($add_id,'1'); // 收货地址
        $odata['or_atime'] = time();  // 下单时间
        $odata['or_gid'] = $prFind['gp_gid'];  // 下单时间
        $order_id = $poident->add($odata);
        if($order_id){
           exit(json_encode(array('status'=>1,'msg'=>'提交成功','url'=>U('Order/propList'))));
        }
    }
    function buydaili(){
        //接收传值
        $usid = session('user_auth.usid');
        $doident = M('daili_order');
        $goid = I("post.gid");    // 商品id
        $nums = I("post.nums",1);  // 商品数量
        $spec = I("spec");  // 商品规格


        $dgident = M('daili_goods');
        $uident = M('user');
        $conf = tpCache('sIno');
        $ures = $uident->where("`us_uid`='".$usid."'")->find(); //获取会员信息
        $goods = $dgident->where("`dg_id`='".$goid."'")->find(); //获取商品信息
        $data['do_money'] = $goods['dg_price'];
        $data['do_uid']=$usid;
        $data['do_batch'] = $batch = Date('YmdHis').rand(10000,99999); // 订单编号
        $data['do_goid']=$goid;
        $data['do_num']=$nums;
        $data['do_atime']=time();
        $data['do_gname']=$goods['dg_name'];
        $data['do_wstate']='1';
        $data['do_spec']= $spec;
        $re = $doident->add($data);
        exit(json_encode(array('status'=>1,'data'=>$data['do_batch'])));
    }
    public function dailiOrder(){
        $uid = session('user_auth.usid');
        $batch = trim(I('get.oid'));
        //实例化相关表
        $uident = M('user');
        $dgident = M('daili_goods');
        $doident = M('daili_order');
        $ures = $uident->where("`us_uid`='".$uid."'")->field('us_uid,us_money')->find(); //获取会员信息
        $daili = $doident->where("`do_batch`='".$batch."'")->find(); //获取订单信息
        $goods = $dgident->where("`dg_id`='".$daili['do_goid']."'")->find(); //获取商品信息
        $addre= $this->ajaxAddress($uid);  //收货地址
        $data['do_addre']= serialize($addre);
        $this->assign('ures',$ures);  //会员信息
        $this->assign('ares', $addre);
        $this->assign('goods', $goods);
//        echo '<pre>';
//        print_r($daili);
//        die;
        $this->assign('daili', $daili);
        $this->assign('aid',I('get.aid',$addre['ad_id']));
        $doident->where("`do_batch`='".$batch."'")->save($data);
       $this->display();
    }
    public function paydlOrder(){
        $uid = session('user_auth.usid');
        $add_id = trim(I("post.add_id"));   // 收货地址id
        //实例化相关表
        $usident = M('user');
        $doident = M('daili_order');
        $batch= trim(I('post.batch'));
        $orFind = $doident->where("`do_batch`='".$batch."'")->find();
        $usFind = $usident->where("`us_uid`='".$uid."'")->field('us_money,us_pid,us_pwds')->find();
                    // 判断支付密码
//       if(md5($remark) != $usFind['us_pwds']){
//       $res= array('status'=>-1,'msg'=>'密码错误'); // 返回结果状态
        if($orFind){
        $money = round($usFind['us_money']-$orFind['do_money']);
        if($money<0){
            $res= array('status'=>-1,'info'=>'余额不足，更换支付方式'); // 返回结果状态
            exit(json_encode($res));
        }
        $data['do_wstate']= '2';
        $data['do_ptime'] = time();
        $doident->where("`do_batch`='".$batch."'")->save($data);
        accShopLog($orFind['do_uid'],-$orFind['do_money'],'0','0','0','0','劲宝支付批发订单',$orFind['or_id'],$batch);
        $parentOne = $usident->where(array('us_uid'=>$usFind['us_pid']))->find();
        $setupOne = M('setup')->where(array('se_name'=>'pifaone'))->find();
        $setupTwo = M('setup')->where(array('se_name'=>'pifatwo'))->find();
        $bili_one = bcdiv($setupOne['se_value'],100,2);
        $bili_two = bcdiv($setupTwo['se_value'],100,2);
        $moneyOne = bcmul($orFind['do_money'],$bili_one,2);
        $moneyTwo = bcmul($orFind['do_money'],$bili_two,2);
        $reOne = $usident->where(array('us_uid'=>$usFind['us_pid']))->setInc('us_money',$moneyOne);
        $reTwo = $usident->where(array('us_uid'=>$parentOne['us_pid']))->setInc('us_money',$moneyTwo);


        $res= array('status'=>1,'info'=>'订单支付成功','url'=>'/Home/User/index'); // 返回结果状态
        exit(json_encode($res));
        }else{
            $res= array('status'=>-1,'info'=>'订单记录不存在'); // 返回结果状态
            exit(json_encode($res));
        }
    }


}